package com.boarsoft.dubbo.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ConsumerConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;

@Deprecated
public class DubboUtil {

	static {
		/**
		 * FIX java.io.IOException: No properties file: users.properties or
		 * defaults: defaultUsers.properties found
		 */
		System.setProperty("zookeeper.sasl.client", "false");
	}

	/**
	 * 获取dubbo服务对象
	 * 
	 * @param appName
	 * @param regAddrs
	 *            服务注册地址
	 * @param group
	 *            服务组
	 * @param version
	 *            服务版本
	 * @param clazz
	 *            接口类型
	 * @return 服务对象
	 */
	public static <T> ReferenceConfig<T> getDubboReference(String appName,
			String regAddrs,
			String protocol,
			String serviceId,
			String regGroup,
			String version,
			int timeout,
			int retries,
			String scope,
			Class<T> clazz) {
		// 当前应用配置
		ApplicationConfig application = new ApplicationConfig();
		application.setName(appName);

		// 连接注册中心配置
		String[] regAddrArray = regAddrs.split(",");
		List<RegistryConfig> registries = new ArrayList<RegistryConfig>(regAddrArray.length);
		for (int index = 0; index < regAddrArray.length; index++) {
			RegistryConfig registry = new RegistryConfig();

			registry.setProtocol(protocol);
			registry.setAddress(regAddrArray[index]);
			registry.setGroup(regGroup);

			registries.add(registry);
		}

		return getDubboReference(application, registries, serviceId, version, timeout, retries, scope, clazz);
	}

	/**
	 * 获取dubbo服务对象
	 * 
	 * @param appName
	 * @param regAddrs
	 *            服务注册地址
	 * @param group
	 *            服务组
	 * @param version
	 *            服务版本
	 * @param clazz
	 *            接口类型
	 * @return 服务对象
	 */
	public static <T> ReferenceConfig<T> getDubboReference(ApplicationConfig application,
			List<RegistryConfig> registries,
			String serviceGroup,
			String version,
			int timeout,
			int retries,
			String scope,
			Class<T> clazz) {
		// 注意：ReferenceConfig为重对象，内部封装了与注册中心的连接，以及与服务提供方的连接
		// 此实例很重，封装了与注册中心的连接以及与提供者的连接，请自行缓存，否则可能造成内存和连接泄漏
		ReferenceConfig<T> reference = new ReferenceConfig<T>();
		reference.setTimeout(timeout);
		reference.setGroup(serviceGroup);

		reference.setScope(scope);
		reference.setRetries(retries);
		
		reference.setVersion(version);

		reference.setInterface(clazz);
		reference.setRegistries(registries);
		reference.setApplication(application);

		ConsumerConfig consumer = new ConsumerConfig();
		consumer.setCheck(false);

		reference.setConsumer(consumer);

		return reference;
	}

}
